/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;

/**
 *
 * @author ronaldomartins
 */
public abstract class Dao {

    private EntityManager entityManager = null;
    private EntityManagerFactory entityManagerFactory = null;
   
    public EntityManager getEntityManager(){
        if (entityManager == null){
            entityManager = entityManagerFactory.createEntityManager();
        }
        return this.entityManager;
    }

    public  void closeEntityManager(){
        if (entityManager.isOpen()){
           this.entityManager.close();
        }
        if (this.entityManagerFactory.isOpen()){
           this.entityManagerFactory.close();
        }
    }
    
    public Dao() {
        this.entityManagerFactory = 
            Persistence.createEntityManagerFactory("sarencaappPU");
        this.entityManager = getEntityManager();
        
    }
       
    public void inserir(Object object) {
        this.entityManager.getTransaction().begin();
        try {
            this.entityManager.persist(object);
            this.entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            this.entityManager.getTransaction().rollback();
        } 
    }
    
    public void excluir(Object object) {
        this.entityManager.getTransaction().begin();
        try {
            object = this.entityManager.merge(object);
            this.entityManager.remove(object);
            this.entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            this.entityManager.getTransaction().rollback();
        } 
    }    

    public void atualizar(Object object) {
        this.entityManager.getTransaction().begin();
        try {
            object = this.entityManager.merge(object);
            this.entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            this.entityManager.getTransaction().rollback();
        }
    } 
    
    public abstract List listarTodos();
        
    public abstract Object buscarPorId(Long id);   
    
}
